package com.huaxin.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaxin.device.common.UserContext;
import com.huaxin.device.dto.ResponseResult;
import com.huaxin.device.dto.enums.AlarmType;
import com.huaxin.device.dto.request.DeviceAlarmCreateReqDTO;
import com.huaxin.device.dto.request.DeviceAlarmPageListReqDTO;
import com.huaxin.device.mapper.DeviceAlarmMapper;
import com.huaxin.device.mapping.DeviceAlarmMapping;
import com.huaxin.device.models.DeviceAlarm;
import com.huaxin.device.service.DeviceAlarmService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

import static org.springframework.util.StringUtils.hasText;

@Service
@RequiredArgsConstructor
public class DeviceAlarmServiceImpl extends ServiceImpl<DeviceAlarmMapper, DeviceAlarm> implements DeviceAlarmService {
    private final ApplicationContext applicationContext;
    private final DeviceAlarmMapping mapping;

    @Override
    public DeviceAlarm create(DeviceAlarmCreateReqDTO in) {
        if (in == null) {
            return null;
        }
        if (!hasText(in.getDeviceId())) {
            return null;
        }
        if (!hasText(in.getDeviceType())) {
            return null;
        }
        if (!hasText(in.getAlarmType())) {
            return null;
        }
        if (in.getAlarmLevel() == null) {
            return null;
        }
        if (!hasText(in.getRuleId())) {
            return null;
        }
        DeviceAlarm entity = mapping.toEntity(in);
        boolean result = this.save(entity);
        if (result) {
            return this.getById(entity.getId());
        }
        return null;
    }

    @Override
    public DeviceAlarm getByDeviceAlarmId(String id) {
        if (!hasText(id)) {
            throw new IllegalArgumentException("设备报警ID不能为空");
        }
        return this.getById(id);
    }

    @Override
    public DeviceAlarm getLastUnResolvedByDeviceAndType(String deviceId, AlarmType alarmType) {
        LambdaQueryWrapper<DeviceAlarm> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DeviceAlarm::getDeviceId, deviceId)
                .eq(DeviceAlarm::getAlarmType, alarmType)
                .eq(DeviceAlarm::getIsResolved, false);
        return this.getOne(wrapper);
    }

    @Override
    public ResponseResult<IPage<DeviceAlarm>> pageQuery(DeviceAlarmPageListReqDTO in) {
        if (in == null) {
            return ResponseResult.parameterError(null, "分页查询参数不能为空");
        }

        IPage<DeviceAlarm> page = new Page<>(in.getPageNum(), in.getPageSize());
        LambdaQueryWrapper<DeviceAlarm> wrapper = new LambdaQueryWrapper<>();

        // 按设备类型过滤
        if (hasText(in.getDeviceType())) {
            wrapper.eq(DeviceAlarm::getDeviceType, in.getDeviceType());
        }

        // 按设备报警类型过滤
        if (hasText(in.getAlarmType())) {
            wrapper.eq(DeviceAlarm::getAlarmType, in.getAlarmType());
        }

        // 按设备报警等级过滤
        if (in.getAlarmLevel() != null) {
            wrapper.eq(DeviceAlarm::getAlarmLevel, in.getAlarmLevel());
        }

        // 按是否已解决过滤
        if (in.getIsResolved() != null) {
            wrapper.eq(DeviceAlarm::getIsResolved, in.getIsResolved());
        }

        // 按组织家族ID过滤（可选）
        if (hasText(in.getFamilyId())) {
            wrapper.eq(DeviceAlarm::getFamilyId, in.getFamilyId());
        }
        if (hasText(in.getOrgId())) {
            wrapper.eq(DeviceAlarm::getOrgId, in.getOrgId());
        }
        // 按创建时间排序
        wrapper.orderByDesc(DeviceAlarm::getCreatedAt);

        IPage<DeviceAlarm> resultPage = this.page(page, wrapper);
        return ResponseResult.ok(resultPage);
    }

    @Override
    public ResponseResult<Boolean> resolve(String id) {
        if (!hasText(id)) {
            return ResponseResult.parameterError(null, "设备报警ID不能为空");
        }
        DeviceAlarm entity = this.getById(id);
        if (entity == null) {
            return ResponseResult.parameterError(null, "设备报警不存在");
        }
        entity.setIsResolved(true);
        entity.setResolvedAt(LocalDateTime.now());
        entity.setResolvedBy(UserContext.getCurrentUserId());
        return ResponseResult.ok(this.updateById(entity));
    }

    @Override
    public ResponseResult<Boolean> unResolve(String id) {
        if (!hasText(id)) {
            return ResponseResult.parameterError(null, "设备报警ID不能为空");
        }
        DeviceAlarm entity = this.getById(id);
        if (entity == null) {
            return ResponseResult.parameterError(null, "设备报警不存在");
        }
        entity.setIsResolved(false);
        entity.setResolvedAt(null);
        entity.setResolvedBy(null);
        return ResponseResult.ok(this.updateById(entity));
    }
}
